# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import myUser
from .serializers import CustomUserSerializer


# Create your views here.
# class CustomUserListCreateView(generics.ListCreateAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer

"""一、函数式编程 Function Based View"""


# @api_view(["GET", "POST"])
# def CustomUser_list(request):
#     if request.method == "GET":
#         s = CustomUserSerializer(instance=myUser.objects.all(), many=True)
#         return Response(data=s, status=status.HTTP_200_OK)
#     elif request.method == "POST":
#         s = CustomUserSerializer(data=request.data, partial=True)  # 部分更新使用 partial=True:非必填字段可以不填
#         # 反序列化，需要对数据进行校验,因为不确定前端传递过来的数据是否合规
#         if s.is_valid():
#             s.save()
#             return Response(data=s.data, status=status.HTTP_201_CREATED)
#         return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)

"""二、使用通用类视图编程 Generic Class Based View"""
# from rest_framework import generics
# from .models import myUser


# class CustomUserList(generics.ListCreateAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer


# class CusomUserDetail(generics.RetrieveUpdateDestroyAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer


"""三、使用视图集编程 Viewset"""
from rest_framework import viewsets
from .models import myUser


class CustomUserViewSet(viewsets.ModelViewSet):
    queryset = myUser.objects.all()
    serializer_class = CustomUserSerializer


"""# 定义注册新用户视图"""
from rest_framework import generics, permissions
from .serializers import RegisterSerializer


class RegisterView(generics.GenericAPIView):
    authentication_classes = []
    serializer_class = RegisterSerializer
    permission_classes = (permissions.AllowAny,)

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response(
            {
                "user_id": user.id,
                "username": user.username,
                "email": user.email,
                "idcard": user.idcard,
                "company": user.company,
                "department": user.department,
                "workshop": user.workshop,
                "position": user.position,
                "area": user.area,
                "role": user.role,
                "base": user.base,
            },
            status=status.HTTP_201_CREATED,
        )


"""# 定义使用Django信号机制自动生成Token的函数"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from rest_framework.authtoken.models import Token

"""创建用户时自动生成Token"""


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def generate_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


"""JWT登录视图"""
from rest_framework.views import APIView
from common import models
from common.utils.jwt_auth import create_token
from django.contrib import auth


class JwtLoginView(APIView):
    """基于JWT的用户登录"""

    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        user = request.data.get("username")
        pwd = request.data.get("password")
        # user_object = models.myUser.objects.filter(username=user, password=pwd).first()
        # 使用Django自带的认证系统
        user_object = auth.authenticate(request, username=user, password=pwd)
        # print({"id": user_object.id, "name": user_object.username})
        print(type(user_object))
        if not user_object:
            print({"code": 1000, "error": "用户名或密码错误！"})
            return Response(
                {
                    "state": False,
                    "info": "用户名或密码错误！ ₍ᐢ •͈ ༝ •͈ ᐢ₎♡",
                    "data": {"username": user},
                }
            )

        accessToken = create_token({"id": user_object.id, "name": user_object.username}, timeout=100)

        role = user_object.role
        print(role)
        Response_role = []
        Response_role.append(role)

        return Response(
            {
                "state": True,
                "info":"登录成功！ <(￣︶￣)>",
                "data": {
                    "username": user_object.username,
                    "accessToken": accessToken,
                    "roles": Response_role,
                },
            }
        )


class JwtOrderView(APIView):
    """测试通过JWT认证获取某一个接口数据"""

    def get(self, request, *args, **kwargs):
        print(request.user)

        return Response("订单列表！获取成功！")


"""刷新Token接口"""


class RefreshTokenView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        refreshToken = request.data.get("refreshToken")
        if refreshToken:
            return Response(
                {
                    "state": True,
                    "data": {
                        "accessToken": "eyJhbGciOiJIUzUxMiJ9.newAdmin",
                        "refreshToken": "eyJhbGciOiJIUzUxMiJ9.newAdminRefresh",
                        # `expires`选择这种日期格式是为了方便调试，后端直接设置时间戳或许更方便（每次都应该递增）。如果后端返回的是时间戳格式，前端开发请来到这个目录`src/utils/auth.ts`，把第`38`行的代码换成expires = data.expires即可。
                        "expires": "2030/10/30 23:59:59",
                    },
                }
            )
        else:
            return Response({"success": False, "data": {}})


"""前端动态路由接口"""


class AsyncRoutesView(APIView):
    authentication_classes = []
    permission_classes = []
    permissionRouter = [
        {
            "path": "/permission",
            "meta": {"title": "menus.permission", "icon": "ep:lollipop", "rank": 199},
            "children": [
                {"path": "/permission/page/index", "name": "PermissionPage", "meta": {"title": "menus.permissionPage", "roles": ["admin", "权限管理"]}},
                {
                    "path": "/permission/button/index",
                    "name": "PermissionButton",
                    "meta": {
                        "title": "menus.permissionButton",
                        "showParent": "true",
                        "roles": ["admin", "权限管理"],
                        "auths": ["permission:btn:add", "permission:btn:edit", "permission:btn:delete"],
                    },
                },
            ],
        },
    ]

    def get(self, request, *args, **kwargs):
        return Response({"success": True, "data": self.permissionRouter})
